package com.estun.backroundManagementService.modules.product.service.impl;

import com.alibaba.excel.util.DateUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.estun.backroundManagementService.modules.alarm.mapper.AlarmMapper;
import com.estun.backroundManagementService.modules.alarm.model.StationAlarm;
import com.estun.backroundManagementService.modules.alarm.service.StationAlarmService;
import com.estun.backroundManagementService.modules.product.dto.ProductStatDTO;
import com.estun.backroundManagementService.modules.product.mapper.ProductMapper;
import com.estun.backroundManagementService.modules.product.model.Product;
import com.estun.backroundManagementService.modules.product.model.res.ProductRecord;
import com.estun.backroundManagementService.modules.product.request.ProductRequest;
import com.estun.backroundManagementService.modules.product.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 产品表 服务实现类
 * </p>
 *
 * @author machine
 * @since 2023-02-14
 */
@Slf4j
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private AlarmMapper stationAlarmMapper;

    @Autowired
    private StationAlarmService stationAlarmService;

    @Override
    public Map<String, Object> getProductStat(String currentDate) {
        List<LocalDateTime> timeRange = getTimeRange();
        LocalDateTime startOfDay = timeRange.get(0);
        LocalDateTime endOfDay = timeRange.get(1);
        List<Product> productList = getProductList(startOfDay, endOfDay);
        List<StationAlarm> alarmList = getAlarmList(startOfDay, endOfDay);
        Map<String, Long> productStat = groupProductStatus(productList);
        productStat.put("totalSize", (long) productList.size());
        Map<Integer, Map<String, Long>> hourStatusCountMap = countProductStatus(productList);
        Map<Integer, Long> hourAlarmDurationMap = calculateAlarmDurations(alarmList);
        List<Map<String, Object>> productStatDetail = generateResult(hourStatusCountMap, hourAlarmDurationMap);
        Map<String, Object> map = new HashMap<>();
        map.put("productStat", productStat);
        map.put("productStatDetail", productStatDetail);

        Long l = queryProductForCurrentMonth();
        map.put("currentMonthNum", l);
        return map;
    }

    private Long queryProductForCurrentMonth() {
        LocalDateTime startOfMonth = getStartOfMonth();
        LocalDateTime endOfMonth = getEndOfMonth();

        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.between("create_time", startOfMonth, endOfMonth);
        queryWrapper.eq("type", 1);
        queryWrapper.eq("status", 1);
        return productMapper.selectCount(queryWrapper);
    }

    // 获取当前月份的起始时间
    private LocalDateTime getStartOfMonth() {
        return LocalDateTime.now().withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
    }

    // 获取当前月份的结束时间
    private LocalDateTime getEndOfMonth() {
        return LocalDateTime.now().withDayOfMonth(LocalDateTime.now().getMonth().maxLength()).withHour(23).withMinute(59).withSecond(59).withNano(999999999);
    }

    public static List<LocalDateTime> getTimeRange() {
        List<LocalDateTime> timeRange = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime startTime0 = now.plusDays(-1).toLocalDate().atTime(20, 30);
        LocalDateTime endTime0 = now.toLocalDate().atTime(8, 30);
        LocalDateTime startTime1 = now.toLocalDate().atTime(8, 30);
        LocalDateTime endTime1 = now.toLocalDate().atTime(20, 30);
        LocalDateTime startTime2 = now.toLocalDate().atTime(20, 30);
        LocalDateTime endTime2 = now.plusDays(1).toLocalDate().atTime(8, 30);
        if (now.isAfter(startTime0) && now.isBefore(endTime0)) {
            timeRange.add(startTime0);
            timeRange.add(endTime0);
        }
        if (now.isAfter(startTime1) && now.isBefore(endTime1)) {
            timeRange.add(startTime1);
            timeRange.add(endTime1);
        } else if (now.isAfter(startTime2) && now.isBefore(endTime2)) {
            timeRange.add(startTime2);
            timeRange.add(endTime2);
        }
        return timeRange;
    }

    public static List<LocalDateTime> getTimeRange(LocalDateTime now) {
        List<LocalDateTime> timeRange = new ArrayList<>();
        LocalDateTime startTime0 = now.plusDays(-1).toLocalDate().atTime(20, 30);
        LocalDateTime endTime0 = now.toLocalDate().atTime(8, 30);
        LocalDateTime startTime1 = now.toLocalDate().atTime(8, 30);
        LocalDateTime endTime1 = now.toLocalDate().atTime(20, 30);
        LocalDateTime startTime2 = now.toLocalDate().atTime(20, 30);
        LocalDateTime endTime2 = now.plusDays(1).toLocalDate().atTime(8, 30);
        if (now.isAfter(startTime0) && now.isBefore(endTime0)) {
            timeRange.add(startTime0);
            timeRange.add(endTime0);
        }
        if (now.isAfter(startTime1) && now.isBefore(endTime1)) {
            timeRange.add(startTime1);
            timeRange.add(endTime1);
        } else if (now.isAfter(startTime2) && now.isBefore(endTime2)) {
            timeRange.add(startTime2);
            timeRange.add(endTime2);
        }
        return timeRange;
    }

    public static void main(String[] args) {
//        LocalDateTime now = LocalDateTime.of(2024, 3, 1, 1, 50, 8, 663);
//        List<LocalDateTime> timeRange = getTimeRange(now);
//        if (timeRange.isEmpty()) {
//            System.out.println("timeRange is empty");
//        } else {
//            System.out.println("timeRange: " + timeRange);
//        }

//        LocalDateTime time = getStartOfPreviousHalfHour(0);
//        System.out.println("time:"+time);
    }

    @Override
    public List<ProductStatDTO> getProductStatByCycle(ProductRequest productRequest) {

        List<ProductStatDTO> statDTOList = statNumByDay(productRequest.getQuery().getCycle(),
                productRequest.getQuery().getStationId(),
                productRequest.getQuery().getBeginDate(),
                productRequest.getQuery().getEndDate());


        List<ProductStatDTO> statTotalNumByDay = statTotalNumByDay(productRequest.getQuery().getCycle(),
                productRequest.getQuery().getStationId(),
                productRequest.getQuery().getBeginDate(),
                productRequest.getQuery().getEndDate());
        fillCountsByStatus(productRequest, statDTOList, statTotalNumByDay);

        if (CollectionUtils.isNotEmpty(statTotalNumByDay)) {
            return statTotalNumByDay;
        } else {
            return Collections.emptyList();
        }
    }

    @Override
    public Page<ProductStatDTO> pageProductStatByCycle(ProductRequest productRequest) {
        List<ProductStatDTO> statDTOList = statNumByDay(productRequest.getQuery().getCycle(),
                productRequest.getQuery().getStationId(),
                productRequest.getQuery().getBeginDate(),
                productRequest.getQuery().getEndDate());

        Page<ProductStatDTO> statTotalNumByDayPage = statTotalNumByDayPage(productRequest.getQuery().getCycle(),
                productRequest.getQuery().getStationId(),
                productRequest.getQuery().getBeginDate(),
                productRequest.getQuery().getEndDate(),
                productRequest.getPage(),
                productRequest.getSize());

        if (!CollectionUtils.isEmpty(statDTOList)) {
            fillCountsByStatus(productRequest, statDTOList, statTotalNumByDayPage.getRecords());
        }
        return statTotalNumByDayPage;
    }


    public void fillCountsByStatus(ProductRequest productRequest, List<ProductStatDTO> statDTOList, List<ProductStatDTO> statTotalNumByDay) {
        long time1 = System.currentTimeMillis();
        //获取所需要计算的数据
        Map<String, List<ProductStatDTO>> stationIdMap = statDTOList.stream().collect(Collectors.groupingBy(ProductStatDTO::getStationId));
        List<String> stationIds = new ArrayList<>(stationIdMap.keySet());

        if (CollectionUtils.isEmpty(statTotalNumByDay)) {
            return;
        }

        statTotalNumByDay = statTotalNumByDay.stream()
                .sorted(Comparator.comparing(ProductStatDTO::getFormattedCreateTime)).collect(Collectors.toList());

        String begin = productRequest.getQuery().getBeginDate();
        String end = productRequest.getQuery().getEndDate();

        if (begin.length() > 7) {
            LocalDate beginLocalDate = LocalDate.parse(begin, DateTimeFormatter.ofPattern(DateUtils.DATE_FORMAT_10));
            LocalDate endLocalDate = LocalDate.parse(end, DateTimeFormatter.ofPattern(DateUtils.DATE_FORMAT_10));

            begin = beginLocalDate.atStartOfDay().format(DateTimeFormatter.ofPattern(DateUtils.DATE_FORMAT_19));
            end = endLocalDate.atTime(23, 59, 59).format(DateTimeFormatter.ofPattern(DateUtils.DATE_FORMAT_19));
        } else {
            YearMonth beginMonth = YearMonth.parse(begin);
            YearMonth endMonth = YearMonth.parse(end);

            begin = beginMonth.atDay(1).atStartOfDay().format(DateTimeFormatter.ofPattern(DateUtils.DATE_FORMAT_19));
            end = endMonth.atEndOfMonth().atTime(23, 59, 59).format(DateTimeFormatter.ofPattern(DateUtils.DATE_FORMAT_19));
        }
        long time2 = System.currentTimeMillis();
        System.out.println(time2 - time1);
        List<StationAlarm> stationAlarmList = stationAlarmService.getAlarmListByStationIdList(stationIds, begin, end);
        long time3 = System.currentTimeMillis();
        System.out.println(time3 - time2);
        statTotalNumByDay.forEach(totalDTO -> {
            String currentDate = totalDTO.getFormattedCreateTime();
            List<ProductStatDTO> statSubDTOList = statDTOList.stream()
                    .filter(statDTO -> statDTO.getFormattedCreateTime().equals(currentDate))
                    .collect(Collectors.toList());

            statSubDTOList.forEach(obj -> {
                if (obj.getStatus() == -1) {
                    totalDTO.setUnqualifiedNum(totalDTO.getUnqualifiedNum() + obj.getCount());
                } else if (obj.getStatus() == 1) {
                    totalDTO.setQualifiedNum(totalDTO.getQualifiedNum() + obj.getCount());
                } else if (obj.getStatus() == 0) {
                    totalDTO.setProducingNum(totalDTO.getProducingNum() + obj.getCount());
                }

                //计算生产量和合格率
                long total = totalDTO.getQualifiedNum() + totalDTO.getUnqualifiedNum() + totalDTO.getProducingNum();
                totalDTO.setTotal(total);
                double acceptability = 0.0;
                if (total > 0) {
                    acceptability = new BigDecimal(totalDTO.getQualifiedNum())
                            .divide(new BigDecimal(total), 2, BigDecimal.ROUND_HALF_UP)
                            .doubleValue();
                }
                totalDTO.setQualifiedRate(new BigDecimal(acceptability).multiply(new BigDecimal(100)).intValue());
            });

            //计算累计故障时间
            //获取站点列表
            int totalTime = 0;
            for (String stationId : stationIds) {
                //过滤出当前日期的告警数据
                List<StationAlarm> subStationAlarmList = stationAlarmList
                        .stream()
                        .filter(stationAlarm -> stationId.equalsIgnoreCase(stationAlarm.getStationId()))
                        .filter(stationAlarm -> stationAlarm.getUpdateTime().toString().contains(currentDate))
                        .sorted(Comparator.comparing(StationAlarm::getUpdateTime))
                        .collect(Collectors.toList());
                //计算间隔时间
                totalTime += calculateDurationByDate(stationId, subStationAlarmList);
            }
            totalDTO.setAlarmDuration(totalTime);
        });
    }


    public List<ProductStatDTO> statNumByDay(int cycle, String stationId, String begin, String end) {
        String format = "";
        if (cycle == 1) {
            format = "%Y-%m-%d";

        } else if (cycle == 2) {
            format = "%Y-%m";
        }
        if (StringUtils.isBlank(format) || StringUtils.isBlank(begin) || StringUtils.isBlank(end)) {
            return Collections.emptyList();
        }
        List<ProductStatDTO> statDTOList = productMapper.statNumByDay(stationId, format, begin, end);
        return CollectionUtils.isNotEmpty(statDTOList) ? statDTOList : Collections.emptyList();
    }


    public List<ProductStatDTO> statTotalNumByDay(int cycle, String stationId, String begin, String end) {
        String format = "";
        if (cycle == 1) {
            format = "%Y-%m-%d";

        } else if (cycle == 2) {
            format = "%Y-%m";
        }
        if (StringUtils.isBlank(format) || StringUtils.isBlank(begin) || StringUtils.isBlank(end)) {
            return Collections.emptyList();
        }
        List<ProductStatDTO> statDTOList = productMapper.statTotalNumByDay(stationId, format, begin, end);
        return CollectionUtils.isNotEmpty(statDTOList) ? statDTOList : Collections.emptyList();
    }

    public Page<ProductStatDTO> statTotalNumByDayPage(int cycle, String stationId, String begin, String end, int page, int size) {
        Page<ProductStatDTO> productStatDTOPage = new Page<>();
        String format = "";
        if (cycle == 1) {
            format = "%Y-%m-%d";

        } else if (cycle == 2) {
            format = "%Y-%m";
        }
        if (StringUtils.isBlank(format) || StringUtils.isBlank(begin) || StringUtils.isBlank(end)) {
            return productStatDTOPage;
        }
        List<ProductStatDTO> statDTOList = productMapper.statTotalNumByDay(stationId, format, begin, end);
        List<ProductStatDTO> statDTOListPage = productMapper.statTotalNumByDayPage(stationId, format, begin, end, (page - 1) * size, size);

        productStatDTOPage.setTotal(statDTOList.size());
        productStatDTOPage.setRecords(CollectionUtils.isNotEmpty(statDTOListPage) ? statDTOListPage : Collections.emptyList());
        productStatDTOPage.setCurrent(page);
        productStatDTOPage.setSize(size);

        return productStatDTOPage;
    }


    @Override
    public ProductRecord getProductByProductNo(String productNo) {
        QueryWrapper<Product> productQueryWrapper = new QueryWrapper<>();
        productQueryWrapper.eq("product_no", productNo);
        Product product = getOne(productQueryWrapper);
        ProductRecord productRecord = new ProductRecord();
        productRecord.putProduct(product);
        String lowerCode = product.getLowerCode();
        if (StringUtils.isNotBlank(lowerCode)) {
            productRecord.putProduct(getOne(new QueryWrapper<Product>().eq("lower_code", lowerCode).eq("type", 2)));
        }
        return productRecord;
    }


    private List<Product> getProductList(LocalDateTime startOfDay, LocalDateTime endOfDay) {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.between("create_time", startOfDay, endOfDay);
        queryWrapper.eq("type", 1);
        return productMapper.selectList(queryWrapper);
    }

    private List<StationAlarm> getAlarmList(LocalDateTime startOfDay, LocalDateTime endOfDay) {
        QueryWrapper<StationAlarm> queryWrapper = new QueryWrapper<>();
        queryWrapper.between("update_time", startOfDay, endOfDay).orderByAsc("update_time");
        return stationAlarmMapper.selectList(queryWrapper);
    }

    private Map<Integer, Map<String, Long>> countProductStatus(List<Product> productList) {
//        return productList.stream()
//                .collect(Collectors.groupingBy(
//                        product -> getHourOfDate(product.getCreateTime()),
//                        Collectors.groupingBy(
//                                product -> getStatusAsString(product.getStatus()),
//                                Collectors.counting()
//                        )
//                ));

        return productList.stream()
                .collect(Collectors.groupingBy(
                        product -> getCustomTimeUnit(product.getCreateTime()),
                        Collectors.groupingBy(
                                product -> getStatusAsString(product.getStatus()),
                                Collectors.counting()
                        )
                ));

    }


    private Map<String, Long> groupProductStatus(List<Product> productList) {
        return productList.stream()
                .collect(Collectors.groupingBy(
                        product -> getStatusAsString(product.getStatus()),
                        Collectors.counting()
                ));
    }

    private Map<Integer, Long> calculateAlarmDurations(List<StationAlarm> alarmList) {
//        Map<Integer, List<StationAlarm>> collect = alarmList.stream().collect(Collectors.groupingBy(alarm -> getHourOfDateTime(alarm.getUpdateTime())));
        Map<Integer, List<StationAlarm>> collect = alarmList.stream().collect(Collectors.groupingBy(alarm -> getCustomTimeUnit(alarm.getUpdateTime())));
        Map<Integer, Long> map = new HashMap<>();
        Set<String> alarmCodes = new HashSet<>();
        collect.forEach((hour, alarmGroup) -> {
            long l = calculateDuration(alarmGroup, hour, alarmCodes);
            map.put(hour, l);
        });
        return map;
    }


    private List<Map<String, Object>> generateResult(Map<Integer, Map<String, Long>> hourStatusCountMap, Map<Integer, Long> hourAlarmDurationMap) {
        List<Map<String, Object>> result = new ArrayList<>();

        for (int hour = 0; hour < 24; hour++) {
            Map<String, Object> entry = new HashMap<>();
            entry.put("hour", hour);
            entry.put("qualifiedCount", hourStatusCountMap.getOrDefault(hour, Collections.emptyMap()).getOrDefault("qualified", 0L));
            entry.put("unqualifiedCount", hourStatusCountMap.getOrDefault(hour, Collections.emptyMap()).getOrDefault("unqualified", 0L));
            entry.put("producing", hourStatusCountMap.getOrDefault(hour, Collections.emptyMap()).getOrDefault("producing", 0L));
            entry.put("alarmDuration", hourAlarmDurationMap.getOrDefault(hour, 0L));
            result.add(entry);
        }
        return result;
    }


    private long calculateDuration(List<StationAlarm> alarmList, int hour, Set<String> alarmCodes) {

//        LocalDateTime preUpdateTime = getMinOfHour(hour);
        LocalDateTime preUpdateTime = getStartOfPreviousHalfHour(hour);
        long d = 0;
        for (int i = 0; i < alarmList.size(); i++) {
            String code = alarmList.get(i).getStationId() + "_" + alarmList.get(i).getAlarmIndex();
            if (alarmList.get(i).getStatus() == 1 && !alarmCodes.contains(code)) {
                alarmCodes.add(code);
                preUpdateTime = alarmList.get(i).getUpdateTime();
                continue;
            }
            if (alarmList.get(i).getStatus() == 0 && alarmCodes.contains(code)) {
                alarmCodes.remove(code);
                if (alarmCodes.isEmpty() && preUpdateTime != null) {
                    Duration duration = Duration.between(preUpdateTime, alarmList.get(i).getUpdateTime());
                    long millis = duration.getSeconds();
                    d = d + millis;
                    preUpdateTime = alarmList.get(i).getUpdateTime();
                }
            }
        }
        if (!alarmCodes.isEmpty()) {
//            LocalDateTime maxOfHour = getMaxOfHour(hour);
            LocalDateTime maxOfHour = getStartOfNextHalfHour(hour);
            Duration duration = Duration.between(preUpdateTime, maxOfHour);
            long millis = duration.getSeconds();
            d = d + millis;
        }
        return d;
    }

    private long calculateDurationByDate(String stationId, List<StationAlarm> alarmList) {
        Map<String, StationAlarm> stationAlarmMap = new HashMap<>();
        Map<String, List<StationAlarm>> alarmMap = alarmList.stream().collect(Collectors.groupingBy(StationAlarm::getAlarmIndex));
        long totalTime = 0;
        LocalDate currentDate = LocalDate.now();
        for (Map.Entry<String, List<StationAlarm>> entry : alarmMap.entrySet()) {
            List<StationAlarm> stationAlarms = entry.getValue();
            long durationTime = 0;
            for (StationAlarm stationAlarm : stationAlarms) {
                //取出该站点该类型第一次告警记录
                String code = stationAlarm.getStationId() + "_" + stationAlarm.getAlarmIndex();
                StationAlarm preStationAlarm = stationAlarmMap.get(code);
                //告警状态
                if (stationAlarm.getStatus() == 1) {
                    if (preStationAlarm != null) {
                        continue;
                    }
                    stationAlarmMap.put(code, stationAlarm);
                } else if (stationAlarm.getStatus() == 0) {
                    if (preStationAlarm != null) {
                        LocalDateTime preAlarmTime = preStationAlarm.getUpdateTime();
                        LocalDateTime alarmTime = stationAlarm.getUpdateTime();

                        long millis = 0l;
                        //计算间隔时间
                        if (preAlarmTime.getDayOfMonth() != alarmTime.getDayOfMonth()) {
                            //如果间隔时间已经跨天则只算前一天到它当天最晚的时间间隔
                            Duration duration = Duration.between(preAlarmTime, preAlarmTime.toLocalDate().plusDays(1).atStartOfDay());
                            millis = duration.getSeconds();
                        } else {
                            //同一天就正常计算
                            Duration duration = Duration.between(preAlarmTime, alarmTime);
                            millis = duration.getSeconds();
                        }
                        durationTime = durationTime + millis;
                        stationAlarmMap.remove(code);
                    }
                }
                log.info("{},{} duration time is {}", stationId, stationAlarm.getAlarmIndex(), durationTime);
            }
            totalTime += durationTime;
        }

        long lastTime = 0l;
        //如果有告警一直到循环结束都没有找到结束指令，就只算到当天最晚时间
        if (!stationAlarmMap.isEmpty()) {
            for (StationAlarm stationAlarm : stationAlarmMap.values()) {
                LocalDateTime start = stationAlarm.getUpdateTime();
                LocalDateTime end = start.toLocalDate().plusDays(1).atStartOfDay();
                //且不是今天的时间,因为还没结束
                if (start.getDayOfMonth() != currentDate.getDayOfMonth()) {
                    Duration duration = Duration.between(start, end);
                    lastTime += duration.getSeconds();
                }
            }
        }
        totalTime += lastTime;
        return totalTime;
    }


    public LocalDateTime getStartOfPreviousHalfHour(int hour) {
//        LocalDateTime currentDateTime = LocalDateTime.now();
//        LocalDateTime resultDateTime;
//        resultDateTime = currentDateTime.minusMinutes(30).withSecond(0).withNano(0);
//        resultDateTime = resultDateTime.withHour(hour).withMinute(30);

        LocalDateTime currentDateTime = LocalDateTime.now();
        // 如果当前小时是 0，向前推一天
        if (hour == 0) {
            currentDateTime = currentDateTime.minusDays(1);
        }
        LocalDateTime targetDateTime = LocalDateTime.of(currentDateTime.getYear(), currentDateTime.getMonth(),
                currentDateTime.getDayOfMonth(), hour, 0);

        // 往前推半小时
        LocalDateTime resultDateTime = targetDateTime.minusMinutes(30);
        return resultDateTime;
    }




    public LocalDateTime getStartOfNextHalfHour(int hour) {
        LocalDateTime currentDateTime = LocalDateTime.now();
        LocalDateTime targetDateTime = LocalDateTime.of(currentDateTime.getYear(), currentDateTime.getMonth(),
                currentDateTime.getDayOfMonth(), hour, 0);

        // 往前推半小时
        LocalDateTime resultDateTime = targetDateTime.plusMinutes(30);
        return resultDateTime;//
    }


    private int getCustomTimeUnit(LocalDateTime time) {
        int hour = time.getHour();
        int minute = time.getMinute();
//        if (minute >= 30) {
//            return hour + 1;
//        } else {
//            return hour;
//        }
        int nextHour;
        // 判断下一小时
        if (minute >= 30) {
            nextHour = hour + 1;
        } else {
            nextHour = hour;
        }
        // 如果下一小时是 24，则重置为 0
        if (nextHour == 24) {
            nextHour = 0;
        }
        return nextHour;
    }


    private int getHourOfDate(LocalDateTime date) {
        return date.getHour();
    }


    private int getHourOfDateTime(LocalDateTime dateTime) {
        return dateTime.getHour();
    }

    private static LocalDateTime getMaxOfHour(int hour) {
        return LocalDateTime.of(LocalDateTime.now().toLocalDate(), LocalTime.of(hour, 59, 59, 999999999));
    }

    private static LocalDateTime getMinOfHour(int hour) {
        return LocalDateTime.of(LocalDateTime.now().toLocalDate(), LocalTime.of(hour, 0, 0, 0));
    }

    private String getStatusAsString(Integer status) {
        switch (status) {
            case 1:
                return "qualified";
            case -1:
                return "unqualified";
            case 0:
                return "producing";
            default:
                return "Unknown";
        }
    }

}
